<template>
  <div
    class="component"
    :class="`${item.key} ${item.element.classStyle}`"
    :data-key="item.key"
    :style="style"
    @contextmenu="rightClick($event, item)"
  >
    <div v-if="isBrush" class="brush" @click.prevent.stop="formatBrushClick(item)">
      <a-button variant="outline" size="large"><span class="bi-magic-line" /></a-button>
    </div>
    <component :ref="setItemRef" :is="item.name" v-bind="bindItem" :key="item.key" />
  </div>
</template>

<script setup>
import { useMenus, useBrush, useComponent, useVisual } from "@/hooks/userEditor"
const { componentListRef, previewData } = useComponent()
const { commonStyle } = useVisual()
const { rightClick } = useMenus()
const { isBrush, formatBrushClick } = useBrush()
const attrs = useAttrs()
const { item } = attrs
const { element, data } = item
const bindItem = computed(() => {
  return {
    data: item.data,
    element: item.element,
    key: item.key,
    name: item.name,
    option: item.option
  }
})
const style = computed(() => {
  const style = {
    width: `${element.width}px`,
    height: `${element.height}px`,
    transform: `translate(${element.left}px, ${element.top}px) rotate(${element.rotate}deg)`,
    zIndex: element.zIndex,
    opacity: element.opacity,
    //隐藏
    visibility: element.hidden ? "hidden" : "visible",
    color: commonStyle.value.theme === "dark" ? "#fff" : "#000"
  }
  if (element.perspective && element.matrix3d) {
    style.transform += `matrix3d(${element.matrix3d.toString()})`
  }
  if (element.backgroundColor) {
    style.background = element.backgroundColor
  }
  if (element.backgroundImage) {
    style.backgroundImage = `url(${element.backgroundImage})`
    style.backgroundSize = element.backgroundSize || "100% 100%"
    style.backgroundRepeat = "no-repeat"
  }
  return style
})
const setItemRef = async (el) => {
  await nextTick()
  if (el) {
    componentListRef[item.key] = el
    setTimeout(() => {
      previewData(item)
    }, 100)
  }
}
const timer = ref(null)
watch(
  () => [data.isPollingInterval, data.pollingInterval],
  ([newVal, pollingInterval]) => {
    if (newVal && pollingInterval) {
      timer.value = setInterval(() => {
        previewData(item)
      }, pollingInterval * 1000)
    } else {
      clearInterval(timer.value)
    }
  }
)
onBeforeUnmount(() => {
  clearInterval(timer.value)
})
</script>

<style scoped lang="less">
// 格式刷遮罩
.brush {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: dashed 1px #000;
  z-index: 999;
  box-sizing: border-box;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: auto;
}
</style>
